<template>
  <div class="admin-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="searchParams.username" placeholder="请输入用户名" clearable>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-input v-model="searchParams.title" placeholder="请输入文章标题" clearable>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="searchByTitleAndUsername">搜索</el-button>
          <el-button type="success" @click="showAddDialog">新增</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 信息展示区 -->
    <div class="table-container">
      <el-table :data="tableData" style="width: 100%" border v-if="tableData.length > 0">
        <el-table-column prop="title" label="文章标题" width="180">
        </el-table-column>
        <el-table-column prop="username" label="用户名">
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间">
          <template slot-scope="scope">
            {{ formatDate(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="update_time" label="更新时间">
          <template slot-scope="scope">
            {{ formatDate(scope.row.update_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-else class="no-data">
        <p>没有找到匹配的数据</p>
      </div>
    </div>
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="currentPage" :page-size.sync="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="allData.length">
      </el-pagination>
    </div>
    <!-- 编辑对话框 -->
    <el-dialog title="编辑文章" :visible.sync="editDialogVisible" width="30%" v-if="currentRow"
      @close="currentRow = null">
      <el-form :model="currentRow" :rules="editRules" ref="editForm">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="currentRow.title"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="currentRow.username"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate">更新</el-button>
      </span>
    </el-dialog>
    <!-- 新增对话框 -->
    <el-dialog title="新增文章" :visible.sync="addDialogVisible" width="30%">
      <el-form :model="addArticle" :rules="addRules" ref="addForm">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="addArticle.title"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addArticle.username"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="addArticle.content"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import {
  Input,
  Row,
  Col,
  Button,
  Table,
  TableColumn,
  Dialog,
  Form,
  FormItem,
  Pagination,
  Message
} from 'element-ui';

export default {
  name: 'ArticleTable',
  components: {
    'el-input': Input,
    'el-row': Row,
    'el-col': Col,
    'el-button': Button,
    'el-table': Table,
    'el-table-column': TableColumn,
    'el-dialog': Dialog,
    'el-form': Form,
    'el-form-item': FormItem,
    'el-pagination': Pagination
  },
  data() {
    return {
      allData: [], // 存储所有数据
      tableData: [], // 存储当前页的数据
      searchParams: {
        username: '',
        title: ''
      },
      editDialogVisible: false,
      currentRow: {
        title: '',
        username: '',
        id: null,
        content: ''
      },
      addDialogVisible: false,
      addArticle: {
        title: '',
        username: '',
        content: ''
      },
      editRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 3, max: 50, message: '文章标题长度为3-50个字符', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 15, message: '用户名长度为3-15个字符', trigger: 'blur' }
        ]
      },
      addRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 3, max: 50, message: '文章标题长度为3-50个字符', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 15, message: '用户名长度为3-15个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' },
          { min: 10, max: 2000, message: '文章内容长度为10-2000个字符', trigger: 'blur' }
        ]
      },
      currentPage: 1,
      pageSize: 10,
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      const token = localStorage.getItem('Authorization');
      if (!token) {
        this.$message.error('未授权访问');
        return;
      }
      const headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': token
      };
      axios.get('http://localhost:8887/Petknowledge/findAll', { headers })
        .then(response => {
          if (response.data.code === 200) {
            this.allData = response.data.data.map(item => ({
              title: item.title,
              username: item.username,
              create_time: item.create_time,
              update_time: item.update_time,
              id: item.id,
              content: item.content
            }));            this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
          } else {
            this.$message.error('获取数据失败: ' + response.data.message);
          }
        })
        .catch(error => {
          console.error('请求失败:', error);
          this.$message.error('请求失败，请检查网络或联系管理员');
        });
    },
    formatDate(value) {
      const date = new Date(value);
      return new Intl.DateTimeFormat('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).format(date);
    },
    searchByTitleAndUsername() {
      // 这里需要实现搜索逻辑，可以通过API调用获取数据
      // 此处省略具体实现，仅作示意
      this.fetchData();
    },
    handleEdit(row) {
      if (row) {
        this.currentRow = { ...row };
        this.editDialogVisible = true;
      } else {
        console.error('Error: Row data is null');
      }
    },
    handleUpdate() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          const token = localStorage.getItem('Authorization');
          const headers = {
            'Content-Type': 'application/json',
            'Authorization': token
          };
          // 此处需要实现更新文章的API调用
          // 例如：axios.post('http://localhost:8887/article/update', this.currentRow, { headers })
          this.$message.success('更新成功');
          this.editDialogVisible = false;
          this.fetchData();
        } else {
          this.$message.error('表单验证失败');
        }
      });
    },
    handleDelete(id) {
      this.$confirm('确认删除这条记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const token = localStorage.getItem('Authorization');
        const headers = {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Authorization': token
        };
        // 此处需要实现删除文章的API调用
        // 例如：axios.post('http://localhost:8887/article/delete?id=' + id, null, { headers })
        this.$message.success('删除成功');
        this.fetchData(); // 重新加载数据
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    showAddDialog() {
      this.addDialogVisible = true;
      this.addArticle = {
        title: '',
        username: '',
        content: ''
      };
    },
    handleAdd() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          const token = localStorage.getItem('Authorization');
          const headers = {
            'Content-Type': 'application/json',
            'Authorization': token
          };
          // 此处需要实现新增文章的API调用
          // 例如：axios.post('http://localhost:8887/article/add', this.addArticle, { headers })
          this.$message.success('新增文章成功');
          this.addDialogVisible = false;
          this.fetchData();
        } else {
          this.$message.error('表单验证失败');
        }
      });
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
    },
  }
};
</script>

<style scoped>
.admin-container {
  padding: 20px;
  max-width: 100%;
  overflow-x: auto;
}

.search-bar {
  margin-bottom: 20px;
}

.search-bar .el-row {
  display: flex;
  justify-content: space-between;
}

.search-bar .el-button {
  margin-left: 10px;
}

.table-container {
  margin-top: 20px;
  overflow-x: auto;
}

.no-data {
  text-align: center;
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: left;
}

.dialog-footer {
  text-align: right;
}

.el-dialog__body {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-weight: bold;
}

.el-button--primary {
  background-color: #13ce66;
  border-color: #13ce66;
}

.el-button--primary:hover {
  background-color: #11b55e;
  border-color: #11b55e;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}
</style>